package com.nervenets.template.event;

import com.nervenets.template.enumeration.OperateType;
import com.nervenets.template.enumeration.WealthType;
import com.nervenets.template.service.DataOfMoneyService;
import com.nervenets.template.service.WealthFlowService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@AllArgsConstructor
public class DataOfMoneyEventListener {
    private final DataOfMoneyService dataOfMoneyService;
    private final WealthFlowService wealthFlowService;

    @SneakyThrows
    @Async
    @Order(0)
    @EventListener(DataOfMoneyEvent.class)
    public void handle(DataOfMoneyEvent event) {
        Thread.sleep(1000);

        WealthType wealthType = WealthType.money;
        List<OperateType> operateTypes = new ArrayList<>();
        long startTime = event.getStartOfDayTime();
        long endTime = event.getStartOfDayTime() + 24 * 60 * 60 * 1000L;

        OperateType type = (OperateType) event.getSource();
        long recharge = 0, human = 0, withdraw = 0, refund = 0;
        switch (type) {
            case recharge:
                operateTypes.add(OperateType.recharge);
                recharge = wealthFlowService.sumOf(wealthType, operateTypes, startTime, endTime);
                break;
            case human:
                operateTypes.add(OperateType.human);
                human = wealthFlowService.sumOf(wealthType, operateTypes, startTime, endTime);
                break;
            case withdraw:
                operateTypes.add(OperateType.withdraw);
                withdraw = wealthFlowService.sumOf(wealthType, operateTypes, startTime, endTime);
                break;
            case productBuy:
                break;
            case refund:
                operateTypes.add(OperateType.refund);
                refund = wealthFlowService.sumOf(wealthType, operateTypes, startTime, endTime);
                break;
        }
        dataOfMoneyService.updateData(event.getStartOfDayTime(), recharge, human, withdraw, refund);
    }
}
